import { ElMessage } from 'element-plus'
import { getToken, removeToken } from '@/utils'
import axios from 'axios'
import qs from 'qs'
import router from '@/router'

const service = axios.create({
    baseURL: import.meta.env.VITE_API_URL,
    timeout: 500000
})


service.interceptors.request.use((config: any) => {
     const userToken = getToken()
    if(userToken){
        if (config.headers) {
            userToken ? config.headers["third-session"] = userToken : '';
        }
    }
    // else if(window.location.pathname != '/login' && window.location.pathname != '/AuthorizedToLogIn'){
    //     router.push({ path: '/login' })
    // }
    if(config.method == 'post'){
        config.headers['content-type'] = 'application/json'
        // config.data = qs.stringify(config.data)
    }
    return config
})

let loginOut = false
service.interceptors.response.use(response => {
    const res = response.data

    if (!res.code) return res; // 有些接口没有code,比如blob流文件

    if (res.code === 401) {
        removeToken()
        if(!loginOut){
            loginOut = true
            ElMessage({
                message: '登录过期',
                type: 'warning',
                duration: 5000,
                customClass: 'message-wrap'
            })
            removeToken()
            setTimeout(()=>{
                loginOut = true
                window.location.href = '/'
            }, 1000)
        }
        return Promise.reject(new Error(res.msg || 'Error'))
    }else if (res.code != 200) {
        if(res.code === 999){
            ElMessage({
                message: res.msg || 'Error',
                type: 'error',
                duration: 3000,
                customClass: 'message-wrap'
            })
        }
        return Promise.reject(new Error(res.msg || 'Error'))
    }
    else {
        return res.data
    }
})

export default service
